package com.fary.boot.context.config;

import com.fary.core.env.ConfigurableEnvironment;
import com.fary.core.env.MutablePropertySources;
import com.fary.core.env.PropertySource;

import java.util.Set;
import java.util.function.Consumer;

/**
 * 指定集合中的属性返回null
 */
class FilteredPropertySource extends PropertySource<PropertySource<?>> {

    private final Set<String> filteredProperties;

    FilteredPropertySource(PropertySource<?> original, Set<String> filteredProperties) {
        super(original.getName(), original);
        this.filteredProperties = filteredProperties;
    }

    /**
     * 过滤掉 filteredProperties 里的属性，直接返回 null
     */
    @Override
    public Object getProperty(String name) {
        if (this.filteredProperties.contains(name)) {
            return null;
        }
        return getSource().getProperty(name);
    }

    static void apply(ConfigurableEnvironment environment, String propertySourceName, Set<String> filteredProperties,
                      Consumer<PropertySource<?>> operation) {
        MutablePropertySources propertySources = environment.getPropertySources();
        PropertySource<?> original = propertySources.get(propertySourceName);
        if (original == null) {
            operation.accept(null);
            return;
        }
        propertySources.replace(propertySourceName, new FilteredPropertySource(original, filteredProperties));
        try {
            operation.accept(original);
        } finally {
            propertySources.replace(propertySourceName, original);
        }
    }

}